package com.jiajia.study.product.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.jiajia.common.to.SkuReductionTo;
import com.jiajia.common.to.SpuBoundTo;
import com.jiajia.common.utils.R;
import com.jiajia.study.product.entity.*;
import com.jiajia.study.product.feign.CouponFeignService;
import com.jiajia.study.product.service.*;
import com.jiajia.study.product.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jiajia.common.utils.PageUtils;
import com.jiajia.common.utils.Query;

import com.jiajia.study.product.dao.SpuInfoDao;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {


    @Autowired
    private SpuInfoDescService spuInfoDescService;

    @Autowired
    private SpuImagesService spuImagesService;

    @Autowired
    private AttrService attrService;

    @Autowired
    private ProductAttrValueService productAttrValueService;

    @Autowired
    private CouponFeignService couponFeignService;

    @Autowired
    private SkuInfoService skuInfoService;

    @Autowired
    private SkuImagesService skuImagesService;

    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {

        QueryWrapper<SpuInfoEntity> queryWrapper = new QueryWrapper<>();

        String key = (String)params.get("key");
        if(!StringUtils.isEmpty(key)){
            queryWrapper.and(a -> {
                a.eq("id",key).or().like("spu_name",key);
            });
        }

        String status = (String) params.get("status");
        if(!StringUtils.isEmpty(status)){
            queryWrapper.eq("publish_status",status);
        }



        String brandId = (String) params.get("brandId");
        if(!StringUtils.isEmpty(brandId) && ! "0".equalsIgnoreCase(brandId)){
            queryWrapper.eq("brand_id",brandId);
        }

        String catelogId = (String) params.get("catelogId");
        if(!StringUtils.isEmpty(catelogId) && "0".equalsIgnoreCase(catelogId)){
            queryWrapper.eq("catelog_id",catelogId);
        }

        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    @Override
    public void saveInfo(SpuSaveVo spuInfoVO) {
        // 保存 spu 的基本信息 pms_spu_info
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtil.copyProperties(spuInfoVO,spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        this.save(spuInfoEntity);
        // 保存 spu 的描述信息 pms_spu_info_desc
        List<String> decript = spuInfoVO.getDecript();

        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();

        spuInfoDescEntity.setSpuId(spuInfoEntity.getId());
        spuInfoDescEntity.setDecript(String.join(",",decript));
        spuInfoDescService.save(spuInfoDescEntity);


        // 保存 spu 图片集信息 pms_spu_images
        List<String> images = spuInfoVO.getImages();
        spuImagesService.saveList(spuInfoEntity.getId(),images);

        // 保存 spu 的规格参数 pms_product_attr_value
        List<BaseAttrs> baseAttrs = spuInfoVO.getBaseAttrs();
        List<ProductAttrValueEntity> productAttrValueEntities = baseAttrs.stream().map(item -> {

            ProductAttrValueEntity productAttrValueEntity = new ProductAttrValueEntity();
            productAttrValueEntity.setSpuId(spuInfoEntity.getId());
            productAttrValueEntity.setAttrId(item.getAttrId());

            AttrEntity attrEntity = attrService.getById(item.getAttrId());

            productAttrValueEntity.setAttrName(attrEntity.getAttrName());
            productAttrValueEntity.setSpuId(spuInfoEntity.getId());
            productAttrValueEntity.setQuickShow(item.getShowDesc());
            productAttrValueEntity.setAttrValue(item.getAttrValues());
            return productAttrValueEntity;
        }).collect(Collectors.toList());
        productAttrValueService.saveBatch(productAttrValueEntities);

        // 保存 spu 的积分信息 gulimall_sms  sms-> sms_spu_bounds
        Bounds bounds = spuInfoVO.getBounds();
        SpuBoundTo spuBoundTo = new SpuBoundTo();
        BeanUtil.copyProperties(bounds,spuBoundTo);
        spuBoundTo.setSpuId(spuInfoEntity.getId());

        R r = couponFeignService.saveSpuBounds(spuBoundTo);
        if(r.get("code").equals("0")){
            // todo : 后续优化
            log.error("远程调用优惠券服务失败");
        }
        // 保存 spu 对应的所有的 sku 信息
        List<Skus> skus = spuInfoVO.getSkus();
        if(null != skus && !skus.isEmpty()){
            for (Skus sku : skus) {
                String defaultImage = "";
                for (Images image : sku.getImages()){
                    if(image.getDefaultImg() == 1){
                        defaultImage = image.getImgUrl();
                    }
                }
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtil.copyProperties(sku,skuInfoEntity);
                skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
                skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
                skuInfoEntity.setSaleCount(0L);
                skuInfoEntity.setSpuId(spuInfoDescEntity.getSpuId());
                skuInfoEntity.setSkuDefaultImg(defaultImage);
                skuInfoService.saveSkuInfo(skuInfoEntity);

                Long skuId = skuInfoEntity.getSkuId();

                List<SkuImagesEntity> skuImagesEntities = sku.getImages().stream().map(imagesItem -> {
                            SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                            skuImagesEntity.setSkuId(skuId);
                            skuImagesEntity.setImgUrl(imagesItem.getImgUrl());
                            skuImagesEntity.setDefaultImg(imagesItem.getDefaultImg());
                            return skuImagesEntity;
                        }).filter(item -> !StringUtils.isEmpty(item.getImgUrl()))
                        .collect(Collectors.toList());

                skuImagesService.saveBatch(skuImagesEntities);


                List<Attr> attr = sku.getAttr();

                List<SkuSaleAttrValueEntity> skuSaleAttrValueEntities = attr.stream().map(item -> {
                    SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                    BeanUtil.copyProperties(item, skuSaleAttrValueEntity);
                    skuSaleAttrValueEntity.setSkuId(skuId);

                    return skuSaleAttrValueEntity;
                }).collect(Collectors.toList());


                skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntities);

                SkuReductionTo skuReductionTo = new SkuReductionTo();
                BeanUtil.copyProperties(sku,skuReductionTo);
                skuReductionTo.setSkuId(skuId);

                if(skuReductionTo.getFullCount() > 0 || skuReductionTo.getFullPrice().compareTo(BigDecimal.ZERO) == 1){
                    R saveSkuReductionResult = couponFeignService.saveSkuReduction(skuReductionTo);
                    if(!saveSkuReductionResult.get("code").equals("0")){
                        log.error("远程保存sku优惠券信息失败");
                    }
                }
            }
        }
        // 保存 sku 的基本信息
        // 保存 sku 的图片信息
        // 保存 sku 的销售属性信息 pms_sku_sale_attr_value
        // sku 的优惠、满减等信息 gulimall_sms  -> sms_sku_ladder sms_sku_full_reduction  sms_member_price
    }

}